package com.google.code.server.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.util.Assert;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * Download File Servlet
 * 
 * @author Nadim Benabdenbi
 * 
 */
public class DownloadFileServlet implements HttpHandler {
	
	private final File file;
	
	public DownloadFileServlet(File file) {
		Assert.notNull(file);
		Assert.isTrue(file.exists());
		this.file = file;
	}
	
	public void handle(HttpExchange exchange) throws IOException {
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "application/x-download");
		responseHeaders.set("Content-Disposition", "attachment; filename=" + file.getName());
		
		// Send the file.
		OutputStream out = exchange.getResponseBody();
		InputStream in = new FileInputStream(file);
		byte buffer[] = new byte[1024];
		int size;
		while ((size = in.read(buffer)) > 0) {
			out.write(buffer, 0, size);
		}
		in.close();
		out.close();
	}
}
